//
//  JXPostsDetailCtl.m
//  JiaoX
//
//  Created by yinqy on 15/2/28.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  帖子详情

#import "JXPostsDetailCtl.h"
#import "JXReplyCommentView.h"
#import "PostsHeaderView.h"
#import "CommentCell.h"
#import "MJRefresh.h"
#import "ForumDataTool.h"
#import "EmptyComtView.h"
#import "JXPopMenu.h"
#import "PopMenuListView.h"
#import "CommentUtils.h"
#import "DESSecurity.h"
#import "UIImageView+WebCache.h"
#import "JXComtDetailCtl.h"
#import "JXChatCtl.h"
#import "JXNavigationController.h"
#import "CustomActionSheet.h"
#import "JXLoginRegistCheckController.h"
#import "StringWithHtmlUtil.h"
#import "SelfDataTool.h"
#import "JXChatManager.h"
//回复地址
#define REPLY_URL @"forum/recomment"

@interface JXPostsDetailCtl ()<PostsHeaderViewDelegate,UITableViewDataSource,UITableViewDelegate,JXReplyCommentViewDelegate,CommentCellViewDelegate,PopMenuListViewDelegate,JXPopMenuDelegate,CustomActionSheetDelegate>
{
    PostsHeaderView *_headerView;
    UITableView *_tableView;
    JXReplyCommentView *_replyView;
    NSMutableArray *_commentFrameArray;
    
    NSString *_orderBy;
    
    
    //回复需要用到的东西
    NSString *_commentId;
    NSString *_userIdOther;
    NSString *_userNameOther;
    NSString *_commentType;//回复的类型：0代表回复的是帖子，1代表回复的是主评论，2代表回复的是子评论
    
    //回复主评论的位置
    NSInteger _replySection;
    //回复子评论的位置
    NSInteger _replyIndex;
    
    NSString *_authorId;
    
    PostsDetailsResult *_postsDetailsResult;
    
    
    //分享相关弹出窗体背后的button
    UIButton *_bg_btn;
    CustomActionSheet* sheet;
    NSString *_shareImgUrl;
    UIImageView *_shareImg;

}
@property (nonatomic,strong)BBSPosts *posts;
@property (nonatomic,strong) JXPopMenu *menu;
/**
 * 0帖子内容+第一页所有评论 1第n页评论内容 2第n页楼主评论
 */
@property (nonatomic,assign)int posterType;
@end

@implementation JXPostsDetailCtl
-(instancetype)initWithBBSPosts:(BBSPosts *)posts{
    self = [super init];
    if (self) {
        self.posts = posts;
        _postsId = posts.postsId;
        _shareImgUrl = posts.img.firstObject;
    }
    return self;
}

-(instancetype)initWithPostId:(NSString *)postId{
    self = [super init];
    if (self) {
        _postsId = postId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"帖子详情"];
    [self.view setBackgroundColor:JXGlobalColorBg];
    _orderBy = ASC;
    [self setRightItem];
    [self initView];
    [self requestDataWithLastComtId:@"" posterType:self.posterType orderBy:_orderBy showDialog:YES];
}

-(void)initView{
    _commentFrameArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    [_tableView setHeight:_tableView.height-REPLY_VIEW_HEIGHT];
    [_tableView setTableFooterView:[[UIView alloc]init]];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorColor:SEPARATORCOLOR];
    [self.view addSubview:_tableView];
    
    _replyView = [[JXReplyCommentView alloc]initWithPlaceholder:@"聊聊嘛～"];
    _replyView.x = 0;
    _replyView.y = self.view.height-REPLY_VIEW_HEIGHT;
    _replyView.delegate = self;
    [self.view addSubview:_replyView];
    
    
    PostsHeaderView *headerView = [[PostsHeaderView alloc]initWithBBSPosts:self.posts];
    [_tableView setTableHeaderView:headerView];
    _headerView = headerView;
    _headerView.delegate = self;
    
    [_tableView addFooterWithTarget:self action:@selector(footerRefresh)];

}

-(void)footerRefresh{
    NSString *lastId = @"";
    if (_commentFrameArray.count) {
        CommentViewFrame *fream = [_commentFrameArray lastObject];
        lastId = fream.comtInfo.commentId;
    }
    [self requestDataWithLastComtId:[Utils isBlankString:lastId]?@"":lastId posterType:self.posterType==0?1:self.posterType orderBy:_orderBy showDialog:NO];
}

-(void)requestDataWithLastComtId:(NSString *)lastComtId posterType:(int)posterType orderBy:(NSString *)orderBy showDialog:(BOOL)showDialog{
    
    MBProgressHUD *HUD = nil;
    if (showDialog) {
        HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    }
    [ForumDataTool getPostsInfoWithPostsId:self.postsId lastComtId:lastComtId posterType:posterType orderBy:orderBy success:^(PostsDetailsResult *result) {
        if (HUD) {
            [HUD hide:YES];
        }
        [Utils refreshComplete:_tableView];
        if ([Utils isBlankString:result.data]) {
            if (posterType==0) {//如果用户加载的是内容与第1页评论
                _postsDetailsResult = result;
                _authorId = result.userInfo.userId;
                [_headerView setPostsInfo:result];//设置内容
            }
            if ([Utils isBlankString:lastComtId]) {
                //如果没有上一个，则清除原有的评论
                [_commentFrameArray removeAllObjects];
            }
            [self comtFramesWithData:result];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        if (HUD) {
            [HUD hide:YES];
        }
        [Utils refreshComplete:_tableView];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}

-(void)comtFramesWithData:(PostsDetailsResult *)result{
    for (int i=0; i<result.allComment.count; i++) {
        CommentViewFrame *frame = [[CommentViewFrame alloc]init];
        CommentInfo *comtInfo = result.allComment[i];
        //传递专题数据，计算所有子控件的frame
        frame.comtInfo = comtInfo;
        [_commentFrameArray addObject:frame];
    }
    if(!_commentFrameArray.count && self.posterType!=2)
    {
        [self showFooterView:NO];
        return;
    }
    [_tableView reloadData];
}

-(void)showFooterView:(BOOL)flag{
    if(_commentFrameArray.count || flag){
        [_tableView beginUpdates];
        [_tableView setTableFooterView:[[UIView alloc]init]];
        [_tableView endUpdates];
    }else{
        EmptyComtView *view = [[EmptyComtView alloc]init];
        [_tableView setTableFooterView:view];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _commentFrameArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentCell *cell = [CommentCell cellWithTableView:tableView];
    [cell.comtCellView setTag:indexPath.row];
    [cell.comtCellView setDelegate:self];
    [cell.comtCellView setAuthorId:[NSString stringWithFormat:@"%@",_authorId]];
    [cell setComtframe:_commentFrameArray[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentViewFrame *frame = _commentFrameArray[indexPath.row];
    return frame.frame.size.height;
}

#pragma mark - 私有

/**
 *  设置右边items
 */
-(void)setRightItem{
    UIBarButtonItem *itemAuthor = [UIBarButtonItem itemWithImageName:@"navigationbar_author" highImageName:@"navigationbar_author_highlighted" target:self action:@selector(showAuthor:)];
    UIButton *authorBtn = (UIButton *)itemAuthor.customView;
    [authorBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_author_highlighted"] forState:UIControlStateSelected];
    UIBarButtonItem *itemMore = [UIBarButtonItem itemWithImageName:@"navigationbar_more" highImageName:@"navigationbar_more_highlighted" target:self action:@selector(showMorePop)];
    self.navigationItem.rightBarButtonItems = @[itemMore,itemAuthor];
}


/**
 *  查看楼主回复
 */
-(void)showAuthor:(UIButton *)btn{
    if (btn.isSelected) {
        //查看所有
        self.posterType = 1;
    }else{
        //查看楼主回复
        self.posterType = 2;
    }
    [self requestDataWithLastComtId:@"" posterType:self.posterType orderBy:_orderBy showDialog:YES];
    [btn setSelected:!btn.selected];
    
}

-(void)showMorePop{
    NSMutableArray *array = [NSMutableArray array];
    
    [array addObject:[[PopMenuBean alloc]initWithTitle:@"分享　　" icon:@"ic_pop_menu_share"]];
    [array addObject:[[PopMenuBean alloc]initWithTitle:@"倒序查看" icon:[NSString stringWithFormat:@"ic_pop_menu_%@",_orderBy]]];
    
    PopMenuListView *listView = [[PopMenuListView alloc]initWithItemArray:array];
    listView.delegate = self;
    self.menu = [JXPopMenu popMenuWithContentView:listView];
    self.menu.arrowPosition = JXPopMenuArrowPositionRight;
    self.menu.delegate = self;
    self.menu.dimBackground = YES;
    [self.menu showInRect:CGRectMake(JXScreenW-listView.width-8, NavHeight-3, listView.width, listView.height)];
}

-(void)popMenuItemClick:(NSUInteger)index{
    if (self.menu) {
        [self.menu dismiss];
        self.menu = nil;
    }
    switch (index) {
        case 0:{
            //点击了分享
            [self share];
            break;
        }
        case 1:{
            //点击了倒序查看
            if ([_orderBy isEqualToString:ASC]) {
                _orderBy = DESC;
            }else{
                _orderBy = ASC;
            }
            [self requestDataWithLastComtId:@"" posterType:self.posterType orderBy:_orderBy showDialog:YES];
            break;
        }
    }
}

-(void)share{
    // 弹出分享窗体
    sheet = [[CustomActionSheet alloc] initWithButtons:[NSArray arrayWithObjects:
                                                        [CustomActionSheetButton buttonWithImage:[UIImage imageNamed:@"btn_share_circle"] title:@"朋友圈"],
                                                        [CustomActionSheetButton buttonWithImage:
                                                         [UIImage imageNamed:@"btn_share_wx"] title:@"微信"],
                                                        nil]];
    sheet.delegate = self;
    [sheet showInView:self.view];
    //重新设置高度,并隐藏蒙层
    [_bg_btn setSize:CGSizeMake(JXScreenW, JXScreenH-sheet.height)];
    [_bg_btn setHidden:NO];
}

#pragma mark - 分享窗体的代理
-(void)beforeClick{//点击蒙层
    [sheet dissmiss];
    [_bg_btn setHidden:YES];
}

-(void)choseAtIndex:(NSInteger)index{
    [_bg_btn setHidden:YES];
    //获取想要分享的参数
    NSString* share_root_url = [NSString stringWithFormat:@"%@%@",BASE_URL,POSTS_OR_REVIEWS_SHARE_URL];
    NSString* desReveiwsId = [[[DESSecurity alloc]init] TripleDES:[NSString stringWithFormat:@"%@",_postsId] encryptOrDecrypt:kCCEncrypt];
    desReveiwsId = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)desReveiwsId, nil, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
    NSString* share_title = _postsDetailsResult.posts.title;
    NSString* share_url =  [NSString stringWithFormat:share_root_url,desReveiwsId,2];
    share_url = [share_url stringByReplacingOccurrencesOfString:@"api/" withString:@""];
    
    NSString* share_desc  =  [StringWithHtmlUtil getTextFromHtml:_postsDetailsResult.posts.content];
    if([Utils isBlankString:_shareImgUrl]){//如果传入的图片为空,则从图文中重新取出赋值
        _shareImgUrl = [StringWithHtmlUtil getForumContextFirstImg:_postsDetailsResult.posts.content];
    }
    _shareImg = [[UIImageView alloc]init];
    JXLog(@"url = %@ title = %@ desc = %@ img = %@  DES = %@",share_url,share_title,share_desc,_shareImg,desReveiwsId);
    switch (index) {
        case 0://朋友圈
            if(_shareImg.image){
                [Utils shareToWx:WXSceneTimeline share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
            }else{
                [_shareImg sd_setImageWithURL:[NSURL URLWithString:_shareImgUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    [self judgeShareImg:image];
                    [Utils shareToWx:WXSceneTimeline share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
                }];
            }
            break;
        case 1://微信
            if(_shareImg.image){
                 [Utils shareToWx:WXSceneSession share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
            }else{
                [_shareImg sd_setImageWithURL:[NSURL URLWithString:_shareImgUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    [self judgeShareImg:image];
                    [Utils shareToWx:WXSceneSession share_url:share_url share_title:share_title share_desc:share_desc image:_shareImg.image];
                }];
            }
            break;
            
        default:
            break;
    }
}

#pragma Mark - 论坛评论相关 delegte

-(void)bottomViewReplyBtnClick:(NSString *)replyContent{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    [CommentUtils replyCommentWithController:self replyUrl:REPLY_URL ReplyType:REPLY_TYPE_POSTSID replyMainId:_postsId commentId:_commentId replyContent:replyContent userIdOther:_userIdOther commentType:_commentType success:^(CommentInfo *result) {
        //这儿做了两件事，把键盘关掉，隐藏hud
        [self.view endEditing:YES];
        
        //在这儿处理回复成功相关逻辑
        [CommentUtils replyResultHandle:_commentFrameArray replyType:REPLY_TYPE_POSTSID commentType:_commentType currentComtId:result.commentId userIdOther:_userIdOther userNameOther:_userNameOther replyContent:replyContent section:_replySection orderBy:_orderBy doSomeBefore:^{
            if(_commentFrameArray.count==0){
            [self showFooterView:YES];
        }
        } doSomeAfter:^{
            [_tableView reloadData];
        }];
        
        //处理完逻辑之后重置相关参数，重置完毕之后再将hud关掉，并弹出回复成功tip
        [self reSetReplyParams];[HUD hide:YES];
        if ([result.integral isEqualToString:@"1"]) {
            [DialogUtils showTipsWithView:self.navigationController.view String:@"回复成功\n经验值+1"];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:@"回复成功"];
        }
    } failure:^(NSError *error) {
        [HUD hide:YES];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"回复失败"];
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self reSetReplyParams];
    [self.view endEditing:YES];
}

/**
 *  重置相关回复参数
 */
- (void)reSetReplyParams{
    _commentId = nil;
    _userIdOther = nil;
    _commentType = nil;
    _userNameOther = nil;
    [_replyView setPlaceHolder:nil];
    [_replyView setText:nil];
    _replySection = _replyIndex = -1;
    _commentType = @"0";
}


#pragma mark - 头view的代理方法
-(void)webviewLoadFinish{
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
}

- (void)replyBtnClick:(UIButton *)btn{
    JXLog(@"回复楼主tag=%ld",(long)btn.tag);
    if (btn.tag!=-1) {
        _replySection = btn.tag;
        //回复的是主评论
        _commentType = @"1";
        
        CommentViewFrame *frame = _commentFrameArray[btn.tag];
        _commentId = frame.comtInfo.commentId;
        _userIdOther = frame.comtInfo.commentUserId;
        
        [_replyView setPlaceHolder: [NSString stringWithFormat:@"回复@%@",frame.comtInfo.commentName]];
        [_replyView becomeFirstResponder];
    }else{
        //回复帖子
        [self reSetReplyParams];
        [_replyView becomeFirstResponder];
    }
}

- (void)moreBtnClick:(NSInteger)index{
    JXLog(@"index=%ld",(long)index);
    CommentViewFrame *frame = _commentFrameArray[index];
    
    JXComtDetailCtl *detail = [[JXComtDetailCtl alloc]initWithComtId:frame.comtInfo.commentId ReplyType:@"postsId" replyId:self.postsId startFrom:-1 mainComtInfo:frame.comtInfo];
    [self.navigationController pushViewController:detail animated:YES];
    
}

/**
 *  CELL里面子评论被点击
 *
 *  @param section 点击的第section条主评论
 *  @param index   点击的是第index条子评论
 */
-(void)childReplyItemClick:(NSInteger)section index:(NSInteger)index{
    _replySection = section;_replyIndex = index;
    //回复的是子评论
    _commentType = @"2";
    
    CommentViewFrame *frame = _commentFrameArray[section];
    _commentId = frame.comtInfo.commentId;
    
    CommentInfo *reComt = frame.comtInfo.reComment[index];
    _userIdOther = reComt.commentUserId;
    _userNameOther = reComt.commentName;
    
    [_replyView setPlaceHolder: [NSString stringWithFormat:@"回复@%@",reComt.commentName]];
    
    [_replyView becomeFirstResponder];
}


-(void)childChatItemClick:(NSInteger)section index:(NSInteger)index{
    CommentViewFrame *frame = _commentFrameArray[section];
    _commentId = frame.comtInfo.commentId;
    CommentInfo *reComt = frame.comtInfo.reComment[index];
    
//    UserInfo *info = [[JXChatManager sharedInstance].userInfoDao getUserInfoWithId:reComt.commentUserId];
//    if (info) {`
//        JXChatCtl *chat = [[JXChatCtl alloc]initWithUserInfo:info];
//        [self.navigationController pushViewController:chat animated:YES];
//    }else{
        MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
        [SelfDataTool getUserInfoWithUserId:reComt.commentUserId success:^(UserInfo *result){
            [HUD hide:YES];
            if ([Utils isBlankString:result.data]) {
                JXChatCtl *chat = [[JXChatCtl alloc]initWithUserInfo:result];
                [self.navigationController pushViewController:chat animated:YES];
            }else{
                [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
            }
        } failure:^(NSError *error) {
            [HUD hide:NO];
            [DialogUtils showTipsWithView:self.navigationController.view String:@"获取个人信息失败"];
        }];
//    }
}


/**
 *  主评论的聊天被点击
 *
 *  @param btn
 */
- (void)chatBtnClick:(UIButton *)btn{
    if (!TOKEN) {
        JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginRegistCheckController alloc]init]];
        [self presentViewController:nav animated:YES completion:^{}];
        return;
    }
    UserInfo *userInfo = nil;
    if (btn.tag == -1) {
        userInfo = _postsDetailsResult.userInfo;
    }else{
        userInfo = [[UserInfo alloc]init];
        CommentViewFrame *frame = _commentFrameArray[btn.tag];
        userInfo.userId = frame.comtInfo.commentUserId;
        userInfo.userImg = frame.comtInfo.headImage;
        userInfo.nickName = frame.comtInfo.commentName;
    }
    
    JXChatCtl *chat = [[JXChatCtl alloc]initWithUserInfo:userInfo];
    [self.navigationController pushViewController:chat animated:YES];
}

/**
 *  处理分享的图片
 *
 *  @param image
 */
-(void)judgeShareImg:(UIImage*)image{
    if(image){
        [_shareImg setImage:image];
    }else{
        image = [UIImage imageNamed:@"ic_launcher"];
        [_shareImg setImage:image];
    }
}

-(NSString *)comtReplyType{
    return REPLY_TYPE_POSTSID;
}

@end
